﻿
using BizProxy;
using Creative85.Framework.Data;
using Project32CHE.Biz.CustomerCar;
using Project32CHE.Biz.Goods;
using Project32CHE.Biz.Unionshop;
using Project32CHE.Biz.UserAccount;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ImportForm
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        private void Form1_Load(object sender, EventArgs e)
        {
            //var d = new System.Data.OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\\1.accdb;");
            // d.Open();
            Control.CheckForIllegalCrossThreadCalls = false;
            label16.Text = "";
            label17.Text = "";
            label18.Text = "";
            label19.Text = "";
            label20.Text = "";
            label21.Text = "";
            label22.Text = "";
            label23.Text = "";
            label24.Text = "";
            label25.Text = "";
            init();
        }
        private void init()
        {
            ComboBox[] ServerCombox = new ComboBox[] { comboBox1, comboBox4, comboBox6, comboBox8, comboBox10 };
            foreach (var item in ServerCombox)
            {
                item.DisplayMember = "Item1";
                item.ValueMember = "Item2";
                item.DataSource = new List<Tuple<string, string>> { new Tuple<string, string>("", ""), new Tuple<string, string>("R7", "http://R7.hehe.com"), new Tuple<string, string>("R8", "http://R8.hehe.com") };
                var control = item;
                var allControl = control.Parent.Controls.Cast<Control>();
                var shopid = allControl.Where(u => u.Tag == (object)"shopid").FirstOrDefault() as TextBox;
                var account = allControl.Where(u => u.Tag == (object)"account").FirstOrDefault() as ComboBox;
                shopid.TextChanged += (o, e) =>
                {
                    Guid shopid1;
                    if (string.IsNullOrEmpty(shopid.Text) || !Guid.TryParse(shopid.Text, out shopid1))
                    {
                        account.DataSource = null;
                        account.Items.Clear();
                    }
                    else
                    {
                        if (Guid.TryParse(shopid.Text, out shopid1))
                        {
                            var userlist = UserService.GetUserByShopID(shopid1);
                            account.DataSource = userlist;
                            account.ValueMember = "Id";
                            account.DisplayMember = "AccountName";
                        }
                    }
                };
                item.SelectedValueChanged += (o, e) =>
                {
                    Db.Type = ((Tuple<string, string>)((ComboBox)o).SelectedItem).Item1;
                    shopid.Text = "";
                };
            }
        }

        #region 下载导入模板
        private void button12_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog path = new FolderBrowserDialog();
            path.Description = "请选择下载目录";
            path.ShowNewFolderButton = true;
            path.ShowDialog();
            if (string.IsNullOrEmpty(path.SelectedPath))
            {
                return;
            }
            string filename = path.SelectedPath + "/项目导入模版" + DateTime.Now.ToString("yyyyMMddhhmmsss") + ".xlsx";
            File.Copy(Environment.CurrentDirectory + "/Excels/Sample/项目导入模版.xlsx", filename);
            MessageBox.Show("下载成功！");
        }

        private void button20_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog path = new FolderBrowserDialog();
            path.Description = "请选择下载目录";
            path.ShowNewFolderButton = true;
            path.ShowDialog();
            if (string.IsNullOrEmpty(path.SelectedPath))
            {
                return;
            }
            string filename = path.SelectedPath + "/第三方维修单导入模板" + DateTime.Now.ToString("yyyyMMddhhmmsss") + ".xlsx";
            File.Copy(Environment.CurrentDirectory + "/Excels/Sample/第三方维修单导入模板.xlsx", filename);
            MessageBox.Show("下载成功！");
        }

        private void button16_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog path = new FolderBrowserDialog();
            path.Description = "请选择下载目录";
            path.ShowNewFolderButton = true;
            path.ShowDialog();
            if (string.IsNullOrEmpty(path.SelectedPath))
            {
                return;
            }
            string filename = path.SelectedPath + "/供应商导入模版" + DateTime.Now.ToString("yyyyMMddhhmmsss") + ".xlsx";
            File.Copy(Environment.CurrentDirectory + "/Excels/Sample/供应商导入模版.xlsx", filename);
            MessageBox.Show("下载成功！");
        }

        private void button8_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog path = new FolderBrowserDialog();
            path.Description = "请选择下载目录";
            path.ShowNewFolderButton = true;
            path.ShowDialog();
            if (string.IsNullOrEmpty(path.SelectedPath))
            {
                return;
            }
            string filename = path.SelectedPath + "/客户导入模版" + DateTime.Now.ToString("yyyyMMddhhmmsss") + ".xlsx";
            File.Copy(Environment.CurrentDirectory + "/Excels/Sample/客户导入模版.xlsx", filename);
            MessageBox.Show("下载成功！");
        }

        private void button1_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog path = new FolderBrowserDialog();
            path.Description = "请选择下载目录";
            path.ShowNewFolderButton = true;
            path.ShowDialog();
            if (string.IsNullOrEmpty(path.SelectedPath))
            {
                return;
            }
            string filename = path.SelectedPath + "/商品导入模版" + DateTime.Now.ToString("yyyyMMddhhmmsss") + ".xlsx";
            File.Copy(Environment.CurrentDirectory + "/Excels/Sample/商品导入模版.xlsx", filename);
            MessageBox.Show("下载成功！");
        }
        #endregion

        #region 商品导入
        //上传
        private async void button2_Click(object sender, EventArgs e)
        {
            if (comboBox1.SelectedItem == null)
            {
                MessageBox.Show("请选择一个服务器");
                return;
            }
            if (comboBox2.SelectedItem == null)
            {
                MessageBox.Show("请选择一个用户");
                return;
            }
            var a = openFileDialog1.ShowDialog();
            if (a == DialogResult.OK)
            {
                if (MessageBox.Show("确定上传" + openFileDialog1.FileName + " ？", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Asterisk) == DialogResult.OK)
                {
                    var stream = openFileDialog1.OpenFile();
                    var user = UserService.Get(Guid.Parse(comboBox2.SelectedValue.ToString()));
                    var shopId = user.ShopID;
                    var userName = user.Name;
                    var userId = user.Id;
                    var unionId = user.UnionID;
                    var shop = ShopService.Get(shopId);
                    var time = DateTime.Now;

                    var storages = StorageService.GetStorage(unionId, shopId).ToDictionary(x => x.ID.ToString(), y => y.StorageName, StringComparer.OrdinalIgnoreCase);
                    var categorys = GoodsCategoryService.Get(unionId, shopId);

                    int index = 1;
                    label16.Text = "正在解析Excel，请稍后...";
                    label16.ForeColor = Color.Red;
                    var list = await Task.Run(() =>
                    {
                        var c = ImportService.FromExcel<ImportService.GoodsModel>(stream, true, 1, 10000, ImportService.ConvertGoods, (items, item, i) =>
                        {
                            label21.Text = index + "/" + i;
                            var flag = false;
                            var msg = "";
                            if (item.MatchCarModel != null)
                            {
                                if (item.MatchCarModel.Length > 400)
                                {
                                    msg += "适用车型过长，要求长度为400字符，现长度为:" + item.GoodsCode.Length + "字符";
                                }
                            }
                            if (string.IsNullOrWhiteSpace(item.GoodsCode)) { msg += "商品编码为空。"; }
                            else if (item.GoodsCode.Length > 50)
                            {
                                msg += "商品编码过长，要求长度为50字符，现长度为:" + item.GoodsCode.Length + "字符";
                            }
                            else
                            {
                                if (items.Any(x => x.GoodsCode == item.GoodsCode)) { msg += "商品编码在Excel中重复。"; }
                                if (GoodsService.Get(unionId, shopId, item.GoodsCode) != null) { msg += "商品编码在系统中重复。"; }
                            }
                            if (string.IsNullOrWhiteSpace(item.GoodsName)) { msg += "商品名称为空。"; }
                            else
                            {
                                if (item.GoodsName.Length > 100) { msg += "商品名称过长，要求长度为100字符，现长度为:" + item.GoodsName.Length + "字符"; }
                            }
                            if (!item.InitInventory.HasValue) { msg += "期初库存为空。"; }
                            if (!item.InitCostPrice.HasValue) { msg += "成本价为空。"; }
                            if (string.IsNullOrWhiteSpace(item.StorageName)) { msg += "仓库为空。"; }
                            else
                            {
                                if (!storages.Values.Contains(item.StorageName)) { msg += "仓库不存在。"; } else { item.StorageId = new Guid(storages.Where(u => u.Value == item.StorageName).FirstOrDefault().Key); }
                            }
                            item.UnionID = unionId;
                            item.ShopID = shopId;
                            item.CreateTime = time;
                            item.OperatorName = userName;
                            item.IsDeleted = false;
                            item.IsError = true;
                            if (!string.IsNullOrEmpty(msg))
                            {
                                msg += " ≧ ﹏ ≦ ";
                                flag = true;
                            }
                            item.IsError = flag;
                            item.ErrorMsg = msg;
                            if (!string.IsNullOrWhiteSpace(item.CategoryName))
                            {
                                var category = categorys.Where(x => x.Name.Equals(item.CategoryName)).FirstOrDefault();
                                if (category != null) { item.CategoryID = category.ID; item.CategoryCode = category.Code; }
                            }
                            item.Operate = "删除";
                            item.Index = index;
                            item.ErrorResult = item.IsError ? "错误" : "通过";
                            index++;
                        });
                        return c;
                    });

                    dataGridView1.DataSource = list;
                    label16.Text = "解析成功！";
                    label16.ForeColor = Color.Green;
                }
            }
        }
        //导入
        private void button4_Click(object sender, EventArgs e)
        {
            if (dataGridView1.DataSource == null)
            {
                MessageBox.Show("请选择导入的数据！");
                return;
            }
            var listObj = dataGridView1.DataSource;
            var list = (IEnumerable<ImportService.GoodsModel>)listObj;
            string errorRows = "";
            var rownumber = 1;
            foreach (var item in list)
            {
                if (item.IsError)
                {
                    errorRows += "（" + rownumber + "）";
                }
                rownumber += 1;
            }
            if (!string.IsNullOrWhiteSpace(errorRows))
            {
                MessageBox.Show("您导入的数据列表在第" + errorRows + "行还有错误信息，请在excel中处理后重新导入，或者在本列表中删除错误数据再保存！");
                return;
            }
            if (MessageBox.Show("确定导入该模板？", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Asterisk) == DialogResult.OK)
            {
                var user = UserService.Get(Guid.Parse(comboBox2.SelectedValue.ToString()));
                var shopId = user.ShopID;
                var userName = user.Name;
                var userId = user.Id;
                var unionId = user.UnionID;
                var shop = ShopService.Get(shopId);
                var time = DateTime.Now;
                ImportService.Save(list, x =>
                {
                    x.UnionID = unionId;
                    x.ShopID = shopId;
                    x.CreateTime = time;
                    x.OperatorName = userName;
                    x.IsDeleted = false;
                });
                MessageBox.Show("导入成功！");
            }
        }
        private void dataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
        {
            if (e.RowIndex > -1)
            {
                var fdsf = this.dataGridView1.Rows[e.RowIndex].Cells;
                bool intGrade = Convert.ToBoolean(this.dataGridView1.Rows[e.RowIndex].Cells["IsError"].Value);
                if (intGrade)
                {
                    dataGridView1.Rows[e.RowIndex].DefaultCellStyle.ForeColor = Color.Red;
                }
                else
                {
                    dataGridView1.Rows[e.RowIndex].Cells["错误信息"].Style.ForeColor = Color.Green;
                    dataGridView1.Rows[e.RowIndex].Cells["校验"].Style.ForeColor = Color.Green;
                }
            }
        }
        private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            string action = dataGridView1.Columns[e.ColumnIndex].Name;//操作类型
            if (action == "Delete")
            {
                if (MessageBox.Show("确定删除吗?", "删除提示", MessageBoxButtons.OKCancel) == DialogResult.OK)
                {
                    //获取相应列的数据ID,删除此数据记录      
                    var list = ((IEnumerable<ImportService.GoodsModel>)dataGridView1.DataSource).ToList();
                    list.RemoveAt(e.RowIndex);
                    dataGridView1.DataSource = list;
                }
            }
        }
        #endregion

        #region 客户导入
        //上传
        private async void button5_Click(object sender, EventArgs e)
        {
            if (comboBox4.SelectedItem == null)
            {
                MessageBox.Show("请选择一个服务器");
                return;
            }
            if (comboBox3.SelectedItem == null)
            {
                MessageBox.Show("请选择一个用户");
                return;
            }
            var a = openFileDialog1.ShowDialog();
            if (a == DialogResult.OK)
            {
                if (MessageBox.Show("确定上传" + openFileDialog1.FileName + " ？", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Asterisk) == DialogResult.OK)
                {
                    var stream = openFileDialog1.OpenFile();
                    var user = UserService.Get(Guid.Parse(comboBox3.SelectedValue.ToString()));
                    var shopId = user.ShopID;
                    var userName = user.Name;
                    var userId = user.Id;
                    var unionId = user.UnionID;
                    var shop = ShopService.Get(shopId);
                    var time = DateTime.Now;

                    int index = 1;
                    label17.Text = "正在解析Excel，请稍后...";
                    label17.ForeColor = Color.Red;
                    var list = await Task.Run(() =>
                    {
                        var c = ImportService.FromExcel<ImportService.CustomerCarModel>(stream, true, 1, 10000, ImportService.ConvertCustomerCar, (items, item,i) =>
                        {
                            label22.Text = index + "/" + i;
                            var flag = false;
                            var msg = "";
                            if (string.IsNullOrWhiteSpace(item.Name)) { msg += "客户名称为空。"; }
                            if (string.IsNullOrWhiteSpace(item.MobilePhone)) { msg += "联系手机为空。"; }
                            if (string.IsNullOrWhiteSpace(item.PlateNumber)) { msg += "车牌号为空。"; }
                            else
                            {
                                if (items.Any(x => x.PlateNumber == item.PlateNumber)) { msg += "在Excel中重复。"; }
                            }
                            if (CarService.GetCar(unionId, shopId, item.PlateNumber) != null) { msg += "车牌号在系统中重复。"; }
                            if (!string.IsNullOrEmpty(msg))
                            {
                                msg += " ≧ ﹏ ≦ ";
                                flag = true;
                            }
                            item.Shop = shop;
                            item.User = user;
                            item.CreateTime = time;
                            item.IsError = flag;
                            item.ErrorMsg = msg;
                            item.Index = index;
                            item.ErrorResult = item.IsError ? "错误" : "通过";
                            item.Operate = "删除";
                            index++;
                        });
                        return c;
                    });
                    dataGridView2.DataSource = list;
                    label17.Text = "解析成功！";
                    label17.ForeColor = Color.Green;
                }
            }
        }
        private void dataGridView2_CellPainting(object sender, System.Windows.Forms.DataGridViewCellPaintingEventArgs e)
        {
            if (e.RowIndex > -1)
            {
                var fdsf = this.dataGridView2.Rows[e.RowIndex].Cells;
                bool intGrade = Convert.ToBoolean(this.dataGridView2.Rows[e.RowIndex].Cells["CusIsError"].Value);
                if (intGrade)
                {
                    dataGridView2.Rows[e.RowIndex].DefaultCellStyle.ForeColor = Color.Red;
                }
                else
                {
                    dataGridView2.Rows[e.RowIndex].Cells["dataGridViewTextBoxColumn17"].Style.ForeColor = Color.Green;
                    dataGridView2.Rows[e.RowIndex].Cells["dataGridViewTextBoxColumn16"].Style.ForeColor = Color.Green;
                }
            }
        }
        private void dataGridView2_CellClick(object sender, System.Windows.Forms.DataGridViewCellEventArgs e)
        {
            string action = dataGridView2.Columns[e.ColumnIndex].Name;//操作类型
            if (action == "DeleteCust")
            {
                if (MessageBox.Show("确定删除吗?", "删除提示", MessageBoxButtons.OKCancel) == DialogResult.OK)
                {
                    //获取相应列的数据ID,删除此数据记录      
                    var list = ((IEnumerable<ImportService.CustomerCarModel>)dataGridView2.DataSource).ToList();
                    list.RemoveAt(e.RowIndex);
                    dataGridView2.DataSource = list;
                }
            }
        }
        //导入
        private void button3_Click(object sender, EventArgs e)
        {
            if (dataGridView2.DataSource == null)
            {
                MessageBox.Show("请选择导入的数据！");
                return;
            }
            var listObj = dataGridView2.DataSource;
            var list = (IEnumerable<ImportService.CustomerCarModel>)listObj;
            string errorRows = "";
            var rownumber = 1;
            foreach (var item in list)
            {
                if (item.IsError)
                {
                    errorRows += "（" + rownumber + "）";
                }
                rownumber += 1;
            }
            if (!string.IsNullOrWhiteSpace(errorRows))
            {
                MessageBox.Show("您导入的数据列表在第" + errorRows + "行还有错误信息，请在excel中处理后重新导入，或者在本列表中删除错误数据再保存！");
                return;
            }
            if (MessageBox.Show("确定导入该模板？", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Asterisk) == DialogResult.OK)
            {
                var user = UserService.Get(Guid.Parse(comboBox3.SelectedValue.ToString()));
                var shopId = user.ShopID;
                var userName = user.Name;
                var userId = user.Id;
                var unionId = user.UnionID;
                var shop = ShopService.Get(shopId);
                var time = DateTime.Now;
                ImportService.Save(list, x =>
                {
                    x.Shop = shop;
                    x.User = user;
                });
                MessageBox.Show("导入成功！");
            }
        }
        #endregion

        #region 项目导入
        //上传
        private async void button7_Click(object sender, EventArgs e)
        {
            if (comboBox6.SelectedItem == null)
            {
                MessageBox.Show("请选择一个服务器");
                return;
            }
            if (comboBox5.SelectedItem == null)
            {
                MessageBox.Show("请选择一个用户");
                return;
            }
            var a = openFileDialog1.ShowDialog();
            if (a == DialogResult.OK)
            {
                if (MessageBox.Show("确定上传" + openFileDialog1.FileName + " ？", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Asterisk) == DialogResult.OK)
                {
                    var stream = openFileDialog1.OpenFile();
                    var user = UserService.Get(Guid.Parse(comboBox5.SelectedValue.ToString()));
                    var shopId = user.ShopID;
                    var userName = user.Name;
                    var userId = user.Id;
                    var unionId = user.UnionID;
                    var shop = ShopService.Get(shopId);
                    var time = DateTime.Now;

                    int index = 1;
                    label18.Text = "正在解析Excel，请稍后...";
                    label18.ForeColor = Color.Red;
                    var list = await Task.Run(() =>
                    {
                        var c = ImportService.FromExcel<ImportService.ItemModel>(stream, true, 1, 10000, ImportService.ConvertItem, (items, item,i) =>
                        {
                            label23.Text = index + "/" + i;
                            var flag = false;
                            var msg = "";
                            if (string.IsNullOrWhiteSpace(item.ItemCode)) { msg += "项目编码为空。"; }
                            if (string.IsNullOrWhiteSpace(item.ItemName)) { msg += "项目名称为空。"; }
                            if (string.IsNullOrWhiteSpace(item.CategoryName)) { msg += "项目分类为空。"; }
                            else
                            {
                                if (items.Any(x => x.ItemCode == item.ItemCode)) { msg += "项目编码在Excel中重复。"; }
                                else
                                {
                                    if (ItemService.Get(shopId, item.ItemCode) != null) { msg += "项目编码在系统中重复。"; }
                                }
                            }
                            if (!string.IsNullOrEmpty(msg))
                            {
                                msg += " ≧ ﹏ ≦ ";
                                flag = true;
                            }
                            item.CreateTime = time;
                            item.IsDeleted = false;
                            item.ShopID = shopId;
                            item.UnionID = unionId;
                            item.IsError = flag;
                            item.ErrorMsg = msg;
                            item.Index = index;
                            item.ErrorResult = item.IsError ? "错误" : "通过";
                            item.Operate = "删除";
                            index++;
                        });
                        return c;
                    });
                    dataGridView3.DataSource = list;
                    label18.Text = "解析成功！";
                    label18.ForeColor = Color.Green;
                }
            }
        }
        private void dataGridView3_CellPainting(object sender, System.Windows.Forms.DataGridViewCellPaintingEventArgs e)
        {
            if (e.RowIndex > -1)
            {
                var fdsf = this.dataGridView3.Rows[e.RowIndex].Cells;
                bool intGrade = Convert.ToBoolean(this.dataGridView3.Rows[e.RowIndex].Cells["ItemIsError"].Value);
                if (intGrade)
                {
                    dataGridView3.Rows[e.RowIndex].DefaultCellStyle.ForeColor = Color.Red;
                }
                else
                {
                    dataGridView3.Rows[e.RowIndex].Cells["ItemErrorMsg"].Style.ForeColor = Color.Green;
                    dataGridView3.Rows[e.RowIndex].Cells["ItemError"].Style.ForeColor = Color.Green;
                }
            }
        }
        private void dataGridView3_CellClick(object sender, System.Windows.Forms.DataGridViewCellEventArgs e)
        {
            string action = dataGridView3.Columns[e.ColumnIndex].Name;//操作类型
            if (action == "DeleteItem")
            {
                if (MessageBox.Show("确定删除吗?", "删除提示", MessageBoxButtons.OKCancel) == DialogResult.OK)
                {
                    //获取相应列的数据ID,删除此数据记录      
                    var list = ((IEnumerable<ImportService.ItemModel>)dataGridView3.DataSource).ToList();
                    list.RemoveAt(e.RowIndex);
                    dataGridView3.DataSource = list;
                }
            }
        }
        //导入
        private void button6_Click(object sender, EventArgs e)
        {
            if (dataGridView3.DataSource == null)
            {
                MessageBox.Show("请选择导入的数据！");
                return;
            }
            var listObj = dataGridView3.DataSource;
            var list = (IEnumerable<ImportService.ItemModel>)listObj;
            string errorRows = "";
            var rownumber = 1;
            foreach (var item in list)
            {
                if (item.IsError)
                {
                    errorRows += "（" + rownumber + "）";
                }
                rownumber += 1;
            }
            if (!string.IsNullOrWhiteSpace(errorRows))
            {
                MessageBox.Show("您导入的数据列表在第" + errorRows + "行还有错误信息，请在excel中处理后重新导入，或者在本列表中删除错误数据再保存！");
                return;
            }
            if (MessageBox.Show("确定导入该模板？", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Asterisk) == DialogResult.OK)
            {
                var user = UserService.Get(Guid.Parse(comboBox5.SelectedValue.ToString()));
                var shopId = user.ShopID;
                var userName = user.Name;
                var userId = user.Id;
                var unionId = user.UnionID;
                var shop = ShopService.Get(shopId);
                var time = DateTime.Now;
                ImportService.Save(list, x =>
                {
                    x.UnionID = unionId;
                    x.ShopID = shopId;
                    x.CreateTime = time;
                    x.IsDeleted = false;
                });
                MessageBox.Show("导入成功！");
            }
        }
        #endregion

        #region 供应商导入
        //上传
        private async void button10_Click(object sender, EventArgs e)
        {
            if (comboBox8.SelectedItem == null)
            {
                MessageBox.Show("请选择一个服务器");
                return;
            }
            if (comboBox7.SelectedItem == null)
            {
                MessageBox.Show("请选择一个用户");
                return;
            }
            var a = openFileDialog1.ShowDialog();
            if (a == DialogResult.OK)
            {
                if (MessageBox.Show("确定上传" + openFileDialog1.FileName + " ？", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Asterisk) == DialogResult.OK)
                {
                    var stream = openFileDialog1.OpenFile();
                    var user = UserService.Get(Guid.Parse(comboBox7.SelectedValue.ToString()));
                    var shopId = user.ShopID;
                    var userName = user.Name;
                    var userId = user.Id;
                    var unionId = user.UnionID;
                    var shop = ShopService.Get(shopId);
                    var time = DateTime.Now;

                    int index = 1;
                    label19.Text = "正在解析Excel，请稍后...";
                    label19.ForeColor = Color.Red;
                    var list = await Task.Run(() =>
                    {
                        var c = ImportService.FromExcel<ImportService.SupplierModel>(stream, true, 1, 10000, ImportService.ConvertSupplier, (items, item,i) =>
                        {
                            label24.Text = index + "/" + i;
                            var flag = false;
                            var msg = "";
                            if (string.IsNullOrWhiteSpace(item.SupplierName)) { msg += "供应商名称为空。"; }
                            else
                            {
                                if (items.Any(x => x.SupplierName == item.SupplierName)) { msg += "供应商名称Excel中重复。"; }
                                if (SupplierService.Get(shopId, item.SupplierName) != null) { msg += "供应商名称在系统中重复。"; }
                            }
                            if (!string.IsNullOrEmpty(msg))
                            {
                                msg += " ≧ ﹏ ≦ ";
                                flag = true;
                            }
                            item.UnionID = unionId;
                            item.ShopID = shopId;
                            item.CreateTime = time;
                            item.IsError = flag;
                            item.ErrorMsg = msg;
                            item.Index = index;
                            item.ErrorResult = item.IsError ? "错误" : "通过";
                            item.Operate = "删除";
                            index++;
                        });
                        return c;
                    });
                    dataGridView4.DataSource = list;
                    label19.Text = "解析成功！";
                    label19.ForeColor = Color.Green;
                }
            }
        }
        private void dataGridView4_CellPainting(object sender, System.Windows.Forms.DataGridViewCellPaintingEventArgs e)
        {
            if (e.RowIndex > -1)
            {
                bool intGrade = Convert.ToBoolean(this.dataGridView4.Rows[e.RowIndex].Cells["SuppIsError"].Value);
                if (intGrade)
                {
                    dataGridView4.Rows[e.RowIndex].DefaultCellStyle.ForeColor = Color.Red;
                }
                else
                {
                    dataGridView4.Rows[e.RowIndex].Cells["SuppErrorMsg"].Style.ForeColor = Color.Green;
                    dataGridView4.Rows[e.RowIndex].Cells["SuppError"].Style.ForeColor = Color.Green;
                }
            }
        }
        private void dataGridView4_CellClick(object sender, System.Windows.Forms.DataGridViewCellEventArgs e)
        {
            string action = dataGridView4.Columns[e.ColumnIndex].Name;//操作类型
            if (action == "DeleteSupp")
            {
                if (MessageBox.Show("确定删除吗?", "删除提示", MessageBoxButtons.OKCancel) == DialogResult.OK)
                {
                    //获取相应列的数据ID,删除此数据记录      
                    var list = ((IEnumerable<ImportService.ItemModel>)dataGridView4.DataSource).ToList();
                    list.RemoveAt(e.RowIndex);
                    dataGridView4.DataSource = list;
                }
            }
        }
        //导入
        private void button9_Click(object sender, EventArgs e)
        {
            if (dataGridView4.DataSource == null)
            {
                MessageBox.Show("请选择导入的数据！");
                return;
            }
            var listObj = dataGridView4.DataSource;
            var list = (IEnumerable<ImportService.SupplierModel>)listObj;
            string errorRows = "";
            var rownumber = 1;
            foreach (var item in list)
            {
                if (item.IsError)
                {
                    errorRows += "（" + rownumber + "）";
                }
                rownumber += 1;
            }
            if (!string.IsNullOrWhiteSpace(errorRows))
            {
                MessageBox.Show("您导入的数据列表在第" + errorRows + "行还有错误信息，请在excel中处理后重新导入，或者在本列表中删除错误数据再保存！");
                return;
            }
            if (MessageBox.Show("确定导入该模板？", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Asterisk) == DialogResult.OK)
            {
                var user = UserService.Get(Guid.Parse(comboBox7.SelectedValue.ToString()));
                var shopId = user.ShopID;
                var userName = user.Name;
                var userId = user.Id;
                var unionId = user.UnionID;
                var shop = ShopService.Get(shopId);
                var time = DateTime.Now;
                ImportService.Save(list, x =>
                {
                    x.UnionID = unionId;
                    x.ShopID = shopId;
                    x.CreateTime = time;
                });
                MessageBox.Show("导入成功！");
            }
        }
        #endregion

        #region 第三方维修单导入
        //上传
        private async void button13_Click(object sender, EventArgs e)
        {
            if (comboBox10.SelectedItem == null)
            {
                MessageBox.Show("请选择一个服务器");
                return;
            }
            if (comboBox9.SelectedItem == null)
            {
                MessageBox.Show("请选择一个用户");
                return;
            }
            var a = openFileDialog1.ShowDialog();
            if (a == DialogResult.OK)
            {
                if (MessageBox.Show("确定上传" + openFileDialog1.FileName + " ？", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Asterisk) == DialogResult.OK)
                {
                    var stream = openFileDialog1.OpenFile();
                    var user = UserService.Get(Guid.Parse(comboBox9.SelectedValue.ToString()));
                    var shopId = user.ShopID;
                    var userName = user.Name;
                    var userId = user.Id;
                    var unionId = user.UnionID;
                    var shop = ShopService.Get(shopId);
                    var time = DateTime.Now;

                    int index = 1;
                    label20.Text = "正在解析Excel，请稍后...";
                    label20.ForeColor = Color.Red;
                    var list = await Task.Run(() =>
                    {
                        var c = ImportService.FromExcel<ImportService.BillExtSheetModel>(stream, true, 1, 10000, ImportService.ConvertBillExtSheet, (items, item,i) =>
                        {
                            label25.Text = index + "/" + i;
                            var flag = false;
                                var msg = "";
                                if (string.IsNullOrWhiteSpace(item.BillCode)) { msg += "单号为空。"; }

                                if (string.IsNullOrEmpty(msg) == false)
                                {
                                    flag = true;
                                }
                                item.UnionID = unionId;
                                item.ShopID = shopId;
                                item.CreateTime = time;
                                item.IsError = flag;
                                item.ErrorMsg = msg;
                                item.Index = index;
                                item.ErrorResult = item.IsError ? "错误" : "通过";
                                item.Operate = "删除";
                                index++;
                            });
                        return c;
                    });
                    dataGridView5.DataSource = list;
                    label20.Text = "解析成功！";
                    label20.ForeColor = Color.Green;
                }
            }
        }
        private void dataGridView5_CellPainting(object sender, System.Windows.Forms.DataGridViewCellPaintingEventArgs e)
        {
            if (e.RowIndex > -1)
            {
                bool intGrade = Convert.ToBoolean(this.dataGridView5.Rows[e.RowIndex].Cells["BillIsError"].Value);
                if (intGrade)
                {
                    dataGridView5.Rows[e.RowIndex].DefaultCellStyle.ForeColor = Color.Red;
                }
                else
                {
                    dataGridView5.Rows[e.RowIndex].Cells["BillErrorMsg"].Style.ForeColor = Color.Green;
                    dataGridView5.Rows[e.RowIndex].Cells["BillError"].Style.ForeColor = Color.Green;
                }
            }
        }
        private void dataGridView5_CellClick(object sender, System.Windows.Forms.DataGridViewCellEventArgs e)
        {
            string action = dataGridView5.Columns[e.ColumnIndex].Name;//操作类型
            if (action == "DeleteBill")
            {
                if (MessageBox.Show("确定删除吗?", "删除提示", MessageBoxButtons.OKCancel) == DialogResult.OK)
                {
                    //获取相应列的数据ID,删除此数据记录      
                    var list = ((IEnumerable<ImportService.ItemModel>)dataGridView5.DataSource).ToList();
                    list.RemoveAt(e.RowIndex);
                    dataGridView5.DataSource = list;
                }
            }
        }
        //导入
        private void button11_Click(object sender, EventArgs e)
        {
            if (dataGridView5.DataSource == null)
            {
                MessageBox.Show("请选择导入的数据！");
                return;
            }
            var listObj = dataGridView5.DataSource;
            var list = (IEnumerable<ImportService.BillExtSheetModel>)listObj;
            string errorRows = "";
            var rownumber = 1;
            foreach (var item in list)
            {
                if (item.IsError)
                {
                    errorRows += "（" + rownumber + "）";
                }
                rownumber += 1;
            }
            if (!string.IsNullOrWhiteSpace(errorRows))
            {
                MessageBox.Show("您导入的数据列表在第" + errorRows + "行还有错误信息，请在excel中处理后重新导入，或者在本列表中删除错误数据再保存！");
                return;
            }
            if (MessageBox.Show("确定导入该模板？", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Asterisk) == DialogResult.OK)
            {
                var user = UserService.Get(Guid.Parse(comboBox9.SelectedValue.ToString()));
                var shopId = user.ShopID;
                var userName = user.Name;
                var userId = user.Id;
                var unionId = user.UnionID;
                var shop = ShopService.Get(shopId);
                var time = DateTime.Now;
                ImportService.Save(list, x =>
                {
                    x.UnionID = unionId;
                    x.ShopID = shopId;
                    x.CreateTime = time;
                });
                MessageBox.Show("导入成功！");
            }
        }
        #endregion
    }
}
